package com.ruyiadmin.springboot.service_layer.implementations.framework_implementations;

import com.alibaba.fastjson.JSON;
import com.ruyiadmin.springboot.common_infrastructure.properties.QuartzConfig;
import com.ruyiadmin.springboot.common_infrastructure.classes.ScheduleJobMessage;
import com.ruyiadmin.springboot.common_infrastructure.constants.business.JobAction;
import com.ruyiadmin.springboot.common_infrastructure.exceptions.RuYiAdminCustomException;
import com.ruyiadmin.springboot.service_layer.interfaces.system_interfaces.ISysScheduleJobService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 分布式Redis消息服务实现类
 * </p>
 *
 * @author RuYiAdmin
 * @since 2022-08-04
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class DistributedRedisHostedService implements MessageListener {

    //region 实现类私有属性

    private final QuartzConfig quartzConfig;
    private final ISysScheduleJobService scheduleJobService;

    //endregion

    //region 监听通道消息

    /**
     * 监听通道消息
     * @param msg 消息
     * @param pattern 流
     */
    @Override
    public void onMessage(@NotNull Message msg, byte[] pattern) {
        try {
            log.info("distributed message received:" + msg);
            ScheduleJobMessage message = JSON.parseObject(msg.toString(), ScheduleJobMessage.class);
            if (message.getGroupId() == this.quartzConfig.getGroupId()) {
                switch (message.getAction()) {
                    case JobAction.DELETE:
                        this.scheduleJobService.deleteScheduleJob(message.getJobId(), message.getUserId());
                        break;
                    case JobAction.START:
                        this.scheduleJobService.startScheduleJob(message.getJobId(), message.getUserId());
                        break;
                    case JobAction.PAUSE:
                        this.scheduleJobService.pauseScheduleJob(message.getJobId(), message.getUserId());
                        break;
                    case JobAction.RESUME:
                        this.scheduleJobService.resumeScheduleJob(message.getJobId(), message.getUserId());
                        break;
                    default:
                        break;
                }
            }
        } catch (Exception e) {
            throw new RuYiAdminCustomException(e);
        }
    }

    //endregion

}
